package com.szgd.util;


import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;

import java.io.*;

public class ImageUtil {
    public static void main(String [] args){
        String imgpath = "D:\\szgd-upload-file\\201906\\IMG_20190620_084952-20190620093419.jpg";
        String imgEncoder = ImageUtil.getImageStr(imgpath);
        System.out.println("-----------------");
        System.out.println(imgEncoder);

        //
        //ImageUtil.generateImageByStr(imgEncoder,"D:\\Workspace\\test\\transerExls.xlsx");
    }

    /**
     * 将BASE64编码的文件转换
     * @param encoderStr
     * @param path
     * @return
     */
    public static boolean generateImageByStr(String encoderStr,String path){
        if (encoderStr == null)// 图像数据为空
        return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
        // Base64解码
            byte[] b = decoder.decodeBuffer(encoderStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }
            // 生成jpg图片
            OutputStream out = new FileOutputStream(path);
            out.write(b);
            out.flush();
            out.close();
            return true;
            } catch (Exception e) {
            return false;
        }


    }

    /**
     * 将文件转换成BASE64编码
     * @param imgFile 源文件全路径
     * @return 转换后的BASE64编码
     */
    public static String getImageStr(String imgFile){
        //将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try
        {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
            return "";
        }
        return new String(Base64.encodeBase64(data));

    }

}
